package com.google.code.expr.runtime;

import java.text.NumberFormat;
import java.text.ParseException;

public class EXPRValueConverter {
	private static NumberFormat mNumberFormat;
	
	static {
		mNumberFormat = NumberFormat.getNumberInstance();
	}

	// Serialize from known type
	
	public static String serializeNumber(Number pNumber) {
		return pNumber!=null ? mNumberFormat.format(pNumber) : null;
	}

	public static String serializeBoolean(Boolean pBool) {
		return pBool!=null ? pBool ? Boolean.TRUE.toString() : Boolean.FALSE.toString() : null;
	}

	// parse from known type
	
	public static Boolean parseBoolean(String pBool) {
		return pBool!=null ? new Boolean(pBool).booleanValue() : null;
	}
	public static Number parseNumber(String pNumber) throws ParseException {
		Number number =  mNumberFormat.parse(pNumber);
		if (number instanceof Float || number instanceof Double) {
			return new Double(number.doubleValue());
		}
		else {
			return new Long(number.longValue());
		}
	}
	
	//parse from unknown type
	
	/**
	 * Parses out the contents from a string, creating
	 * the correct value type.
	 */
	public static Object parseUnknown(String pVal) {
		if (pVal!=null) {
			if (pVal.equalsIgnoreCase(Boolean.TRUE.toString())) {
				return Boolean.TRUE;
			}
			else if (pVal.equalsIgnoreCase(Boolean.FALSE.toString())) {
				return Boolean.FALSE;
			}
			else {
				try {
					return parseNumber(pVal);
				}
				catch (ParseException e) {
					return pVal;
				}
			}
		}
		else {
			return null;
		}
	}
}
